<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>字体工具</title>
    <style>
      body {
        text-align: center;
      }
      textarea {
        max-width: 80%;
        width: 800px;
        margin: 20px auto;
        display: block;
        font-size: 20px;
        padding: 10px;
        font-family: 'bear';
      }
      img {
        height: 40px;
        margin: 30px;
      }
    </style>
  </head>
  <body>
    <h1>字体工具</h1>
    <p class="desc">动态生成字体</p>
    <textarea rows="5"></textarea>
    <select> </select>
    <button>生成字体</button>
    <div>
      <img id="select-img" />
    </div>
    <script src="https://hm.baidu.com/hm.js?4dc655ed71352ec8dc3a35a2e9d29283"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="./fonts.js"></script>
    <script>
      const fontSelect = document.querySelector('select')
      const textarea = document.querySelector('textarea')
      const img = document.querySelector('img')
      const apiUrl = '//font.luzhongkuan.cn/api/font/min'
      let selectFont

      // 选择字体
      fontSelect.onchange = function() {
        selectFont = fonts.find(item => item.id == this.value)
        if (!selectFont) return
        img.src = `https://www.luzhongkuan.cn/web/fonts/${selectFont.previewImg}`
      }

      // 字体选项
      createSelect()
      function createSelect() {
        const html = fonts
          .map(item => `<option value="${item.id}">${item.fontName}</option>`)
          .join('')
        fontSelect.innerHTML = `<option value="">请选择</option>${html}`
      }

      // 提交生成字体
      document.querySelector('button').onclick = async () => {
        if (!textarea.value) {
          return alert('请输入需要生成字体的文字')
        }
        if (!selectFont) {
          return alert('请选择字体')
        }
        const {
          data: { data: href }
        } = await createFont(
          textarea.value,
          selectFont.fileName.replace('.ttf', '')
        )
        const _link = document.createElement('link')
        _link.rel = 'stylesheet'
        _link.href = href
        document.head.appendChild(_link)
      }

      // 接口生成字体
      function createFont(text = '', name = '') {
        return axios({
          url: apiUrl,
          method: 'post',
          data: {
            text,
            name,
            fontFamily: 'bear'
          }
        })
      }
    </script>
  </body>
</html>
